import { isArray, isEmpty, isNullOrUnDef, isUndefined } from "@/utils"
import { GetanTableColumnProps, GetanTableProps } from "../types"
import { GetanButtonGroup, GetanButtonGroupProps, GetanButtonProps } from "@/components/ButtonGroup"

/**
 * 使用操作按钮
 */
export function useRowActions(props: Ref<Partial<GetanTableProps>>) {
    // 操作按钮
    const rowActionColumn = computed(() => {
        const { rowActions } = unref(props)
        const actions = rowActions?.actions
        if (isEmpty(rowActions) || isEmpty(actions)) {
            return undefined
        }
        const column = { ...rowActions } as GetanTableColumnProps
        column.property = "__operate__"
        if (isNullOrUnDef(column.title)) {
            column.title = "操作"
        }
        if (isUndefined(column.render)) {
            const style: Recordable = {}
            if (column.align === "center") {
                style.justify = "center"
            } else if (column.align === "right") {
                style.justify = "end"
            }
            column.render = (rowData: Recordable) =>
                h(GetanButtonGroup, { options: parseActionProps(actions as GetanButtonGroupProps | GetanButtonProps[], rowData), ...style })
        }
        return column
    })

    const defaultActionProps: Partial<GetanButtonProps> = {
        border: "text"
    }

    function parseActionProps(actions: GetanButtonGroupProps | GetanButtonProps[], rowData: Recordable) {
        if (isArray(actions)) {
            const actionProps: Partial<GetanButtonGroupProps> = {
                size: "small"
            }
            actionProps.items = (actions as GetanButtonProps[]).map(v => {
                return { ...defaultActionProps, ...v, data: rowData }
            })
            return actionProps
        } else {
            return actions
        }
    }

    return { rowActionColumn }
}
